package com.fancy.learncenter.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonAssignBean;
import com.fancy.learncenter.bean.CartoonListByClassItemBean;
import com.fancy.learncenter.bean.CartoonListByClassListBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.CartoonAssginHomeWorkAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.ui.view.date.custom.DateTimePicker;
import com.fancy.learncenter.ui.view.date.custom.DateTimePickerDialog;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 布置作业
 */
public class CartoonAssignHomeWorkActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.right)
    TextView right;
    @Bind(R.id.right_img)
    ImageView rightImg;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.end_time_text)
    TextView endTimeText;
    @Bind(R.id.not_choose_text)
    TextView notChooseText;
    @Bind(R.id.has_choose_text)
    TextView hasChooseText;
    @Bind(R.id.total_time_text)
    TextView totalTimeText;
    @Bind(R.id.cartoon_ok_text)
    TextView cartoonOkText;
    @Bind(R.id.choose_layout)
    RelativeLayout chooseLayout;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;
    @Bind(R.id.choose_end_text)
    TextView chooseEndText;
    private CartoonAssginHomeWorkAdapter adapter;
    private List<CartoonListByClassItemBean> list;
    private String classId;
    private String homeworkPackageId;
    private String className;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cartoon_assign_home_work, Status.STATUS);
        ButterKnife.bind(this);
        initToolbar("布置作业");
        getIntentData();
        initView();
        initClick();
        initRecycleView();
        initData();
        changePermission();
    }

    private void getIntentData() {

        classId = getIntent().getStringExtra(JumpIntentKey.CLASSID);
        className = getIntent().getStringExtra("className");
    }

    private void initView() {
        title.setText("布置作业");
        chooseEndText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showTimeDialog(chooseEndText);
            }
        });
    }

    private void initClick() {
        cartoonOkText.setOnClickListener(this);
    }


    private void assignHomeWork() {

        String endTime = chooseEndText.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("classId", classId);
        map.put("endTime", endTime);
        map.put("homeworkPackageId", homeworkPackageId);

        HttpMehtod.getInstance().cartoonAssignHomework(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonAssignBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonAssignBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonAssignBean>() {
                    @Override
                    public void success(CartoonAssignBean dataBean) {
                        assigStudentHomework();
                        String homeworkPackageId = dataBean.getHomeworkPackageId();

                        ToastUtil.show("布置作业成功");
                        finish();

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

    }


    private void initRecycleView() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        list = new ArrayList<>();
        adapter = new CartoonAssginHomeWorkAdapter(this, list, classId);
        recyclerView.setAdapter(adapter);
        adapter.setListener(new AlbumImpl() {
            @Override
            public void onClick(int position) {
                homeworkName=list.get(position).getHomeworkPackageName();

                homeworkPackageId = list.get(position).getHomeworkPackageId();

                String homeName = list.get(position).getUnitName();

                hasChooseText.setText("已经选：" + homeName);
            }
        });

    }

    String homeworkName = "";
    String homeworkEndTime = "";

    private void initData() {

        Map<String, Object> map = new HashMap<>();
        map.put("classId", classId);
        HttpMehtod.getInstance().cartoonListHomeworkByClass(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonListByClassListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonListByClassListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonListByClassListBean>() {
                    @Override
                    public void success(CartoonListByClassListBean dataBean) {

                        if (dataBean != null) {
                            list.addAll(dataBean.getResult());
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

    }

    private void assigStudentHomework() {

        Map<String, Object> map = new HashMap<>();
        map.put("classId", classId);
        map.put("className", className);
        map.put("homeworkName", homeworkName);
        map.put("msgType", "2");
        map.put("homeworkEndTime", chooseEndText.getText().toString());
        HttpMehtod.getInstance().assigStudentHomework(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

            }
        });

    }


    private void showTimeDialog(final TextView txv) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String time = sdf.format(new Date());
        final DateTimePickerDialog dialog = DateTimePickerDialog.getInstance(time, "yyyy-MM-dd HH:mm:ss", DateTimePicker.DATE_TIME_PICKER);
        dialog.setListener(new DateTimePickerDialog.OnDateTimePickerListener() {
            @Override
            public void onDateTimePicked(long time) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                txv.setText(sdf.format(new Date(time)));

                chooseLayout.setBackgroundColor(Color.parseColor("#0081A9"));
                cartoonOkText.setTextColor(Color.parseColor("#0081A9"));
            }
        });
        dialog.show(getSupportFragmentManager(), DateTimePickerDialog.TAG + time);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.cartoon_ok_text:
                assignHomeWork();
                break;


        }
    }

    private void changePermission() {
        final PermissionHelper mHelper = new PermissionHelper(this);
        ArrayList<String> permissionList = new ArrayList<>();
        if (!mHelper.hasPermissions(this, Manifest.permission.RECORD_AUDIO)) {
            permissionList.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!mHelper.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        mHelper.requestPermissions("请授予非凡学习文件获取权限！",
                new PermissionHelper.PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
                        LogUtil.MyLog("mHelper", "========确认=======");
                    }

                    @Override
                    public void doAfterDenied(final String... permission) {
                        LogUtil.MyLog("mHelper", "========拒绝=======" + permission.toString());
                        mHelper.showMessageOKCancel(getResources().getString(R.string.recode_permission), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ArrayList<String> permissionList = new ArrayList<>();
                                if (!mHelper.hasPermissions(getBaseContext(), Manifest.permission.RECORD_AUDIO)) {
                                    permissionList.add(Manifest.permission.RECORD_AUDIO);
                                }
                                if (!mHelper.hasPermissions(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                }
                                mHelper.executePermissionsRequest(getBaseContext(), (String[]) permissionList.toArray(new String[permissionList.size()]), mHelper.REQUEST_PERMISSION_CODE);
                            }
                        });
                    }
                }, (String[]) permissionList.toArray(new String[permissionList.size()]));
    }
}
